//引入vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//抽离state
const state = {
    list: [
        { id: 1, name: '吃饭', done: true },
        { id: 2, name: '睡觉', done: false },
        { id: 3, name: '打豆豆', done: true }
    ]
}

//抽离mutation
const mutations = {
    //添加任务
    addTodo(state, payload) {
        //id
        const id = state.list.length === 0 ? 1 : state.list[state.list.length - 1].id + 1;
        // console.log(state);
        //添加
        if (payload.name.trim().length != 0) {
            state.list.push({
                id,
                name: payload.name,
                done: false
            })
        }
    },
    //删除任务
    delTodo(state, payload) {
        state.list = state.list.filter(item => item.id != payload.id)
    },
    //修改状态
    changeStatus(state, payload) {
        //1. 根据id 查找当前任务
        let todo = state.list.find(item => item.id == payload.id);
        //2. 状态取反
        todo.done = !todo.done
    },
    //修改任务
    updateTodo(state, payload) {
        //1. 根据id 找到对应的任务
        let todo = state.list.find(item => item.id == payload.id);
        //2. 修改任务
        todo.name = payload.name
    },
    //清除完成的任务
    clearCompleted(state) {
        //过滤未完成的 重新赋值给list
        state.list = state.list.filter(item => !item.done)
    }
}

//抽离 getter(计算属性)
const getters = {
    //底部的显示与隐藏
    isFooterShow(state) {
        //数组长度大于0 显示
        return state.list.length > 0;
    },
    //剩余未完成的个数
    itemLeftCount(state) {
        return state.list.filter(item => !item.done).length
    },
    //显示与隐藏
    isClearComleted(state) {
        return state.list.some(item => item.done)
    }
}

//抽离actions
const actions = {
    asyncDelTodo(context, payload) {
        setTimeout(() => {
            context.commit('delTodo', payload);
        })
    }
}

//实例化仓库
const store = new Vuex.Store({
    //严格模式
    strict: true,
    //状态
    state,
    mutations,
    getters,
    actions
})

//导出仓库
export default store